package cn.ljserver.project.entity;

import cn.ljserver.tool.weboffice.v3.model.FileInfo;
import lombok.*;
import org.hibernate.proxy.HibernateProxy;

import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import java.time.LocalDateTime;
import java.util.Objects;

@Entity
@Table(name = "t_file")
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Builder
//@NoArgsConstructor
@AllArgsConstructor
public class File {
    @EmbeddedId
    private FileId id;

    private String name;

    private long size;

    private String url;

    private LocalDateTime createTime;

    private LocalDateTime modifyTime;

    @OneToOne
    private User creator;

    @OneToOne
    private User modifier;

    /**
     * 转换为适用与web office的FileInfo
     */
    public FileInfo toFileInfo() {
        return FileInfo.builder()
                .id(this.id.getId())
                .name(this.name)
                .version(this.id.getVersion())
                .size(this.size)
                .createTime(this.createTime)
                .modifyTime(this.modifyTime)
                .creatorId(String.valueOf(this.creator.getId()))
                .modifierId(String.valueOf(this.modifier.getId()))
                .build();
    }

    @Override
    public final boolean equals(Object o) {
        if (this == o) return true;
        if (o == null) return false;
        Class<?> oEffectiveClass = o instanceof HibernateProxy ? ((HibernateProxy) o).getHibernateLazyInitializer().getPersistentClass() : o.getClass();
        Class<?> thisEffectiveClass = this instanceof HibernateProxy ? ((HibernateProxy) this).getHibernateLazyInitializer().getPersistentClass() : this.getClass();
        if (thisEffectiveClass != oEffectiveClass) return false;
        File file = (File) o;
        return getId() != null && Objects.equals(getId(), file.getId());
    }

    @Override
    public final int hashCode() {
        return Objects.hash(id);
    }
}
